import { queryUpdate } from '@/service/sys';
import showModal from './modal';
import { newUpdateDownload } from './draw';
const checkUpdate = async function () {
  let isFull = false;
  /**
   * 安装app更新，版本管理功能可以参考https://uniapp.dcloud.net.cn/uniCloud/upgrade-center.html
   * @param resource 资源包
   */
  const installUpdate = function (resource: string): Promise<PlusRuntimeWidgetInfo> {
    return new Promise((resolve, reject) => {
      plus.runtime.install(
        resource,
        { force: true },
        function onSuccess(widgetInfo) {
          console.log(widgetInfo);
          console.log('安装成功');

          if (!isFull) {
            uni.hideLoading();
            uni.hideToast();
            setTimeout(() => {
              plus.runtime.restart();
            }, 200);
          }
          resolve(widgetInfo);
          uni.removeStorageSync('changeVersion1');
        },
        function onError(error) {
          uni.removeStorageSync('changeVersion1');
          reject(error);
          console.log('安装失败：', error);
        },
      );
    });
  };

  /**
   * 获取本地应用资源信息（版本号等）
   */
  const getWidgetInfo = function (): Promise<PlusRuntimeWidgetInfo> {
    return new Promise((resolve) => {
      plus.runtime.getProperty(plus.runtime.appid as string, function (widgetInfo) {
        resolve(widgetInfo);
      });
    });
  };

  const downloadPack = function (url: string) {
    let showLoading;
    if (url.match(/.*\.apk/)) {
      isFull = true;
      showLoading = plus.nativeUI.showWaiting(`正在下载新版本`, { back: 'none' });
    }
    const downloadTask = uni.downloadFile({
      url,
      success: async (res) => {
        uni.hideLoading();
        try {
          console.log(res.tempFilePath);
          if (uni.getStorageSync('isHide') == 1) {
            uni.setStorageSync('installUpdate', res.tempFilePath);
            uni.removeStorageSync('changeVersion1');
          } else {
            await installUpdate(res.tempFilePath);
          }
          // 重启应用
          // plus.runtime.restart()
        } catch (err) {
          if (isFull) {
            uni.removeStorageSync('changeVersion1');
            uni.showToast({
              title: `安装失败:${err.message}`,
              icon: 'none',
            });
          }
          console.log(err);
        }
      },
      fail: (err) => {
        uni.hideLoading();
        if (isFull && showLoading) {
          showLoading.close();
        }
        console.log('下载失败：', err);
      },
    });

    if (isFull) {
      downloadTask.onProgressUpdate((res) => {
        showLoading.setTitle(`正在下载新版本\n进度：${res.progress}%`);
        if (res.progress >= 100) {
          setTimeout(() => {
            showLoading.close();
          }, 300);
        }
      });
    }
  };

  const widgetinfo = await getWidgetInfo();
  console.log(uni.getStorageSync('changeVersion1'), 11111112222);
  if (uni.getStorageSync('changeVersion1') || uni.getStorageSync('installUpdate')) {
    return;
  }
  const params = {
    // 升级检测数据
    appid: plus.runtime.appid,
    appVersion: widgetinfo.version,
    clientType: 1,
  };
  try {
    const res = await queryUpdate(params);
    console.log(res.data);
    if (res.code === 0 && res.data?.url) {
      // 判断是不是全量更新
      if (res.data.type === 0) {
        try {
          if (uni.getStorageSync('showModal')) return;
          uni.setStorageSync('showModal', '1');
          await uni.showModal({
            title: '有新版本',
            content: res.data.updateSummary || '',
            confirmText: '立即更新',
            showCancel: false,
          });
        } catch (err) {
          console.log(err);
          return;
        }

        try {
          let popView = plus.nativeObj.View.getViewById('popupView');
          popView.close();
        } catch (error) {}

        if (uni.getStorageSync('changeVersion1')) {
          return;
        }
        return newUpdateDownload(res.data, (callbackFun) => {
          uni.removeStorageSync('showModal');
          uni.removeStorageSync('changeVersion1');
          plus.screen.unlockOrientation();
          uni.offWindowResize(callbackFun);
        });
      }
      // console.log(res.data.url);

      downloadPack(res.data.url);
    }
  } catch (error) {
    console.log(error);
  }
};

export default checkUpdate;
